package com.zhentao.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.annotation.Log;
import com.zhentao.dto.system.AssginRoleDto;
import com.zhentao.dto.system.LoginDto;
import com.zhentao.dto.system.SysUserDto;
import com.zhentao.entity.system.SysRoleUser;
import com.zhentao.entity.system.SysUser;
import com.zhentao.mapper.SysUserMapper;
import com.zhentao.mapper.SysUserRoleMapper;
import com.zhentao.service.SysUserService;
import com.zhentao.vo.common.ResultCodeEnum;
import com.zhentao.vo.common.ZhentaoException;
import com.zhentao.vo.system.LoginVo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper,SysUser> implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private RedisTemplate<String , String> redisTemplate;
    @Resource
    private SysUserRoleMapper sysRoleUserMapper;
    /**
     * 登录
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        //校验验证码是否正确
        String captcha = loginDto.getCaptcha();
        //用户输入的验证码
        String codeKey = loginDto.getCodeKey();
        //redis中验证码的数据key
        //从Redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get("user:login:validatecode:" + codeKey);
        if (StrUtil.isEmpty(redisCode)||!StrUtil.equalsIgnoreCase(redisCode,captcha)){
            throw new ZhentaoException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //验证码验证通过删除Redis中的验证码
        redisTemplate.delete("user:login:validatecode:" + codeKey);


        // 根据用户名查询用户
        SysUser sysUser = sysUserMapper.selectByUserName(loginDto.getUserName());
        if(sysUser == null) {
            throw new ZhentaoException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 验证密码是否正确
        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());

        if(!md5InputPassword.equals(sysUser.getPassword())) {
            throw new ZhentaoException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 生成令牌，保存数据到Redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("user:login:" + token , JSON.toJSONString(sysUser) , 30 , TimeUnit.MINUTES);

        // 构建响应结果对象
        LoginVo loginVo = new LoginVo() ;
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        // 返回
        return loginVo;
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        return JSON.parseObject(userJson , SysUser.class) ;
    }

    /**
     * 退出登录
     * @param token
     */
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:"+token);
    }

    @Override
    public Page<SysUser> findByPage(SysUserDto sysUserDto) {
        Page<SysUser> page = new Page<>(sysUserDto.getPageNum(),sysUserDto.getPageSize());
        Page<SysUser> pageInfo = sysUserMapper.findByPage(sysUserDto,page);
        return pageInfo;
    }

    /**
     * 新增用户
     * @param sysUser
     */
    @Override
    public void saveSysUser(SysUser sysUser) {
        // 根据输入的用户名查询用户
        SysUser dbSysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserName,sysUser.getUserName()));
        if(dbSysUser != null) {
            throw new ZhentaoException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        // 对密码进行加密
        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);
        sysUser.setStatus(0);
        sysUserMapper.insert(sysUser);
    }

    /**
     * 修改角色
     * @param sysUser
     */
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateById(sysUser);
    }

    /**
     * 删除用户
     * @param userId
     */
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId);
    }

    /**
     * 保存角色
     * @param assginRoleDto
     */
    @Override
    @Transactional
    public void doAssign(AssginRoleDto assginRoleDto) {
        // 删除之前的所有的用户所对应的角色数据
        sysRoleUserMapper.delete(Wrappers.<SysRoleUser>lambdaQuery().eq(SysRoleUser::getUserId,assginRoleDto.getUserId()));
        // 分配新的角色数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        roleIdList.forEach(roleId->{
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(),roleId);
        });
    }
}